
package com.bfw.utils;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bfw.po.StaffInfo;
import com.bfw.po.StudentInfo;
/**
 * 登录验证的过滤器 servlet3.0新特性（注解）
 */
@WebFilter("/*")
public class LoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public LoginFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		// 获取HttpServletRequest,HttpServletResponse
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res=(HttpServletResponse) response;
		// 获取session
		HttpSession session = req.getSession();
		// 获取当前登录用户信息
		StaffInfo staff = (StaffInfo) session.getAttribute("staff");
		StudentInfo stuinfo = (StudentInfo) session.getAttribute("stuinfo");
		// 获取请求URL信息
		String url = req.getRequestURI();
		if (url.contains("studentphone/login.do")) {
			chain.doFilter(request, response);
			return;
		} 

		if (stuinfo != null) {
			chain.doFilter(request, response);
			return;
		} 

		if (url.contains("/login.do")) {
			chain.doFilter(request, response);
			return;
		}

		if (url.contains("/login_phone.jsp")) {
			chain.doFilter(request, response);
			return;
		} 
		if (url.contains("/resources/")) {
			chain.doFilter(request, response);
			return;
		} 
		if (staff != null) {
			chain.doFilter(request, response);
			return;
		} else {
			if (stuinfo == null && url.contains("/studentphone/")) {
				// 转发页面
				req.getRequestDispatcher("/view/login_phone.jsp").forward(req,
						response);
				return;
			} else {
				//对于非法的请求 一律跳转登录界面
				req.getRequestDispatcher("/view/login.jsp").forward(req,
						response);
				return;
			}
		}



	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
